<?php
class PackageHotelController extends CBaseController
{		
	protected $package;
	public function __construct($config=null) 
    { 
      parent::__construct($config);	  
    } 
		
	public function init($tpl)
	{
		parent::init($tpl);
		$this->reqLogin();
		$this->templator->addViewsDir(dirname(__FILE__).'/../views');
		$this->templator->assign('menu','hotel');
		$this->prepare();
	}
	
	public function prepare()
	{
		if(isset($_GET['id']))
		{
			$id = $_GET['id'];
			$this->package = R::load('travelpackage',$id);
		}
		elseif(isset($_POST['id']))
		{	
			$id = $_POST['id'];
			$this->package = R::load('travelpackage',$id);
		}
		else
		{
			$this->package = R::dispense('travelpackage');
		}
	}
	
	public function assign()
	{		
		$hotel_ids = $_POST['hotel_ids'];	
		foreach($hotel_ids as $hotel_id)
		{
			$days=$_POST[$hotel_id.'_day'];
			$nights=$_POST[$hotel_id.'_night'];
			$mealplan=$_POST[$hotel_id.'_mealplan'];
			$pckgoption_id=$_POST[$hotel_id.'_option'];
			$hotel = R::load('hotel',$hotel_id);			
			R::associate( $this->package, $hotel,array('days'=>$days,'nights'=>$nights,'mealplan'=>$mealplan,'pckgOption_id'=>$pckgoption_id));
		}
		$this->hotels();
	}
	
	public function unassign()
	{
		$hotel_id = $_GET['hotel_id'];
		$hotel = R::load('hotel',$hotel_id);
		R::unassociate( $this->package, $hotel );
		$this->hotels();
	}
	
	public function hotels()
	{		
		$assignedHotels= R::related( $this->package, 'hotel' );
		$assignedHotels=array_merge($assignedHotels, array());
		foreach ($assignedHotels as $hotel) {
			$keys=R::$extAssocManager->related($this->package,'hotel',TRUE,'hotel_id='.$hotel->id);
			$ref=R::load('hotel_travelpackage',$keys[0]);
			$hotel['days']=$ref->days;		
			$hotel['nights']=$ref->nights;		
			$hotel['mealplan']=$ref->mealplan;
			$pckgOptionRef=R::load('pckgOption',$ref->pckgOption_id);
			$hotel['pckgOption']=$pckgOptionRef;		
		}		
		$this->templator->assign('package',$this->package);		
		$this->templator->assign('hotels',$assignedHotels);
		$this->templator->display('hotel/package_hotel.html');
	}
	
	public function select()
	{		
		$assignedHotels= R::related( $this->package, 'hotel' );		
		$allHotels = R::findAll('hotel');
		$hotels =array_diff($allHotels, $assignedHotels);
		$this->templator->assign('package',$this->package);
		$this->templator->assign('pckgOptions',array_merge($this->package->ownPckgOption, array()));
		$this->templator->assign('hotels',array_merge($hotels, array()));
		$this->templator->display('hotel/hotel_list.html');
	}
	
}	